//
//  ST_TIANMsgListViewController.swift
//  btvideo
//
//  Created by Jason on 2021/9/17.
//  Copyright © 2021 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import SwiftyJSON
import SwifterSwift
import NIMSDK
import UserNotifications
import SwiftyUserDefaults
import RealmSwift
//import DifferenceKit
import RxSwift
import RxCocoa


//MARK: -
class ST_TIANMsgListViewController: UIViewController {

    //    MARK: - Life Cycle
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
         
        
        self.view.backgroundColor = .clear
        
        view.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(16)
            make.height.equalTo(ScreenHeight - 150 + 16)
        }
        
        
        view.addSubview(close_view)
        close_view.snp.makeConstraints { (make) in
            make.top.right.left.equalToSuperview()
            make.bottom.equalTo(root_view.snp.top)
        }
        
        root_view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.top.equalToSuperview().offset(20)
            make.centerX.equalToSuperview()
            make.height.equalTo(25)
        }
        
        root_view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().offset(-16)
            make.top.equalToSuperview().offset(65)
        }
        
        bind_data()
    }
    
    
//    MARK: - Properties
    fileprivate lazy var close_view:UIControl = {
        let control = UIControl()
        control.addTarget(self, action: #selector(close_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 16
        return control
    }()
    
    
    fileprivate lazy var titleLabel:UILabel = {
        let control = UILabel.init()
        control.text = "聊天"
        control.textColor = Color.black
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var tableView:UITableView = {
        
        let control = UITableView.init(frame: CGRect.zero, style: UITableView.Style.plain)
        
        control.delegate = self
//        control.dataSource = self
        control.showsVerticalScrollIndicator = false

        control.register(cellWithClass: ST_ConversationListCell.self)
       
        control.separatorStyle = .none
        
        control.backgroundColor = Color.white
        
//        control.backgroundColor = Color.random
        
        control.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 52+BTSafeAreaBottom, right: 0)
        control.showsVerticalScrollIndicator = false
        control.showsHorizontalScrollIndicator = false
        return control
    }()
    
    
    var disposeBag = DisposeBag()
    
    fileprivate lazy var adapter = ST_ConversationAdapter.shared
}

extension ST_TIANMsgListViewController:UITableViewDelegate{
    
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return ST_ConversationListCell.height
    }
    
    /*
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return adapter.sessionList.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withClass: ST_ConversationListCell.self)
        
//        if let m = adapter.sessionList[safe:indexPath.row]{
//            cell.setUp(model: m)
//        }
        
        return cell
    }*/
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        guard let model = adapter.sessionList[safe:indexPath.row],let iCell = cell as? ST_ConversationListCell else{
            return
        }
        
        iCell.bind(model: model)
        
    }
    
    
    
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
        if self.navigationController?.topViewController is ST_PrivateChatViewController{
            
            print("连续点击-----")
            
            return
        }
        
        
        guard let m = adapter.sessionList[safe:indexPath.row] else{ return }
        
        ST_ConversationAdapter.shared.mark_read(sessionId: m.sessionId)
        
        switch m.sessionId {
        
        case LOVE_ASSISTANT_SESSION_ID:
            
            //            男的 不是会员 加蒙层
            if FETCH_MEMBER_STATUS() != .subscribe && ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex == .male {
                            
                popup_membership_controller()
                
                return
            }
            
            let vc = ST_ReceiveLoveModuleController()
            
            self.navigationController?.pushViewController(vc)
//            特质 收到的点赞
        case PECULIARITY_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveThumbUpByEmojiController()

            self.navigationController?.pushViewController(vc)
//            收到的关注
        case FOLLOW_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveFollowViewController()

            self.navigationController?.pushViewController(vc)
//            收到的评论
        case COMMENT_ASSISTANT_SESSION_ID:
            
            let vc = ST_ReceiveCommentsViewController()

            self.navigationController?.pushViewController(vc)
            
        default:
            
            
//            push_to_chat_controller(info: ST_ChatInfoStruct.init(sessionId: m.sessionId, title: m.userName, source: "聊天列表",intimacyImage:m.sweetValueImage), navigationController: self.navigationController)
            if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
                return
            }
            
            
            let provider = BINP
            
            guard let info = try? provider.storage?.object(forKey: m.sessionId) else{
                return
            }
            
            let vc = ST_PrivateChatViewController()
            
            vc.sessionID = m.sessionId
//
            vc.intimacyImage = info.sweetValueImage
            
            vc.source = "聊天列表"
            
            self.navigationController?.pushViewController(vc)
             
        }
    }
    
}


extension ST_TIANMsgListViewController{
    
    @objc fileprivate func close_handle(){
        
        goback_previous_controller()
        
    }
    
    
    fileprivate func bind_data(){
        
        
        adapter.recent_session_observer.bind(to: tableView.rx.items(cellIdentifier: String(describing: ST_ConversationListCell.self))) { index, model, cell in
          
            guard let iCell = cell as? ST_ConversationListCell else{
                return
            }
            
            iCell.bind(model: model)
        }
        .disposed(by: disposeBag)
        
        BINP.update_displaying_subject.debounce(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance).subscribe(onNext: {[weak self] in
            
            self?.update_displaying_cells_data()
            
        }).disposed(by: disposeBag)
        
        
    }
    
    fileprivate func update_displaying_cells_data() {
        
        guard let array = tableView.indexPathsForVisibleRows else { return  }
        
        for indexPath in array{
            
            guard let model = adapter.sessionList[safe:indexPath.row],let iCell = tableView.cellForRow(at: indexPath) as? ST_ConversationListCell else{
                continue
            }
            
            iCell.bind(model: model)
        }
        
    }
    
    
    @objc fileprivate func popup_membership_controller(){
        
        ST_MaidWayManager.shared.source = .遇见_喜欢了我
        
        let vc  = ST_MemberSubscriberController.init(subscribeType: ST_BitianSubscribeType.查看谁喜欢我)

        vc.overCurrentContext = true

        GlobalPresent(toController: vc, animated: false)
    }
}

extension ST_TIANMsgListViewController{
    
    static func toast(){
        
        let nav = PairsCenterInteractiveNavigationController.init(rootViewController: ST_TIANMsgListViewController())
        
        nav.overCurrentContext = true
        
        GlobalPresent(toController: nav)
        
    }
    
}
